<template>
  <!--热力图管理-->
  <el-row style="height:100%">
    <page>
      <pageheader :event="'heatmapPopUp'" :isShow="buttonPermissions.isAdd">
        热力图管理
      </pageheader>
      <div class="page-content">

        <el-card class="box-card tag-card">
           <el-row>
            <Cascader
              :value.sync="waicompany_id_arr"
              :options.sync="waicompanyOptions"
              :width="'300px'"
              :changeEvent="'mallChange'"
              :isClearable="false"
            >所属企业：
            </Cascader>
            <span style="margin-left:10px;">案场选择：</span>
             <el-select v-model="waicase_info_id" filterable placeholder="请选择案场"
                         @change="changeCaseInfo(waicase_info_id,'wai')" :clearable="true" size="small" style="width:300px">
                <el-option
                  v-for="item in waicaseInfoOptions"
                  :key="item.id"
                  :label="item.case_name"
                  :value="item.id">
                </el-option>
              </el-select>
           </el-row>
          <el-table :data="dataTable" size="small" stripe>
            <el-table-column label="序号" type="index" :index="indexMethod" align="center" width="60"></el-table-column>
            <el-table-column label="所属企业" prop="company_name" align="center"></el-table-column>
            <el-table-column label="所属案场" prop="case_info_name" align="center"></el-table-column>
            <el-table-column label="所属楼层" prop="floor_tag_name" align="center"></el-table-column>
            <el-table-column label="操作" prop="id" align="center">
              <template slot-scope="scope">
                <el-button size="small" type="primary" @click="toCoordinate(scope.row)">配置热力图</el-button>
                <el-button size="small" @click="heatData(scope.row)">详情</el-button>
                <el-button size="small" type="danger" @click="heatDel(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <el-dialog v-dialogDrag :title="(isAdd?'新增':'修改')+'热力图'" :visible.sync="isShow" @close="closeDialog"
                   :modal-append-to-body="false" :close-on-click-modal="false" width="800px">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="180px">
            <el-form-item label="选择企业" prop="company_id_arr">
              <Cascader 
                        :disabled="!isAdd"
                        :value.sync="ruleForm.company_id_arr"
                        :options="companyOptions"
                        :changeEvent="'companyChange'"
                        :showAllLevels = 'false'
                        :width="'450px'"
                        :isClearable="false"></Cascader>
            </el-form-item>
            <el-form-item label="选择案场" prop="case_info_id">
              <el-select v-model="ruleForm.case_info_id" filterable placeholder="请选择案场"
                         @change="changeCaseInfo" :disabled="!isAdd" size="small" style="width:450px">
                <el-option
                  v-for="item in caseInfoOptions"
                  :key="item.id"
                  :label="item.case_name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属楼层" prop="floor">
              <el-select v-model="ruleForm.floor" :disabled="!isAdd" filterable placeholder="请选择楼层"
                         size="small" style="width:450px">
                <el-option
                  v-for="item in floorOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id" >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="选择指标" prop="kpi">
              <el-select v-model="ruleForm.kpi"  filterable placeholder="请选择指标"
                         size="small" style="width:450px">
                <el-option
                  v-for="item in kpiOptions"
                  :key="item.key"
                  :label="item.name"
                  :value="item.key" >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="顶峰值"
              prop="top_val"
              :rules="[
                { type: 'number', message: '顶峰值必须为数字值'}
              ]"
            >
              <el-input style="width:200px;margin-right:10px;" size="small" :min="0" :max="100" :disabled="!ruleForm.isTop" v-model.number="ruleForm.top_val"></el-input><el-switch active-text="开"  inactive-text="关" v-model="ruleForm.isTop"></el-switch>
            </el-form-item>
            <el-form-item label="辐射范围"
              prop="radius"
              :rules="[
                { type: 'number', message: '辐射范围必须为数字值'}
              ]"
            >
            <el-input-number  style="width:200px;margin-right:10px;" size="small" :min="10" :max="100" v-model.number="ruleForm.radius"></el-input-number ><span style='font-size:12px;'>默认值为35,最大值：100，最小值：10</span>
            </el-form-item>
            <el-form-item label="上传图纸" prop="dataVal">
              <el-upload
                ref="upload"
                action=""
                accept="image/png,image/jpg,image/jpeg"
                :class="ruleForm.dataVal?'UpFileHidden':''"
                list-type="picture-card"
                :file-list="drawingList"
                :on-preview="(file)=>imgPreview(file)"
                :on-change="(file)=>getFile(file)"
                :on-remove="(file)=>imgRemove(file)"
                :auto-upload="false"
                :show-file-list="true"
                :limit="1"
              >
                <i class="el-icon-plus"></i>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件，图片大小不能超过5M</div>
              </el-upload>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="isShow = false" size="small">取 消</el-button>
            <el-button type="primary" @click="confirmDialog('ruleForm')" size="small">保 存</el-button>
          </div>
        </el-dialog>

        <el-dialog v-dialogDrag :visible.sync="dialogVisible" title="上传图纸">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </div>
    </page>
  </el-row>
</template>
<style lang="scss">
  .page-content {
    .tag-card{
      >.el-card__body{
        >.el-row{
          margin-bottom: 12px;
        }
      }
    }
    padding: 15px;
    .fr {
      float: right;
    }
    .el-table {
      margin-bottom: 10px;
    }
    .paging {
      margin: 15px;
      height: 28px;
    }
    .tag-search{
      width: 40%;
      display: inline-block;
    }
    .tag-search .search-input{
      width: 300px;
      display: inline-block;
    }
    .tag-search .tag-name{
      font-size: 14px;
    }
  }
  .UpFileHidden{
    .el-upload--picture-card{
      display: none;
    }
  }
</style>
<script>
  import page from "@/components/page/page";
  import pageheader from "@/components/page/pageheader";
  import TreeTable from "@/components/common/treeTable";
  import SearchInput from "@/components/sys/assembly/searchinput";
  import Cascader from "@/components/sys/assembly/elcascader";
  export default {
    data() {  
      return {
        pageTitle: "热力图管理",
        isShow: false,//是否显示模态框
        qiyeIdarr:[], //详情所用
        waicompanyOptions:[],//外面表格处企业列表
        waicompany_id_arr:[],//外面企业选中列表
        waicompany_id:'',
        waicaseInfoOptions:[], //外面案场列表       
        waicase_info_id:'', //外面案场选中
        companyOptions:[],//企业列表
        caseInfoOptions:[],//案场列表
        floorOptions:[],//楼层列表
        kpiOptions:[],  //指标列表
        floorId:'', //临时id
        ruleForm:{
          company_id_arr:[],//选中企业数组
          company_id:'',//选中企业
          case_info_id:'',//选中案场数组
          floor:'',//选择楼层
          kpi:'', //选择指标
          dataVal:'',//图片地址
          top_val:0,
          isTop:false,
          radius:35,        //辐射范围
          
        },
        rules: {
          company_id_arr: [{ required: true, message: "请选择所属企业",trigger:'change'}],
          case_info_id : [{ required: true, message: "请选择案场",trigger:'change'}],
          floor : [{ required: true, message: "请选择楼层",trigger:'change'}],
          dataVal: [{ required: true, message: "请添加图片",trigger:'change'}],
        },//form表单验证
        drawingShow:false,//
        dialogImageUrl:'',//
        dialogVisible:false,//
        drawingList:[], //图片列表
        isAdd:true ,    //是否新增
        dataTable:[],
        nowId:'',
        buttonPermissions:{
          isAdd:true,
          isDel:false,
        },
      }
    },
    inject: ["reload"],
    components: {
      page,
      pageheader,
      SearchInput,//搜索框组件
      Cascader,//级联选择器组件
    },
    created() {
      this.$Bus.$emit('Loading',true);
      this.getCompanyTree('wai');
    },
    mounted() {
        //新增按钮
      this.$Bus.$on('heatmapPopUp',() =>{
        this.isShow = true;
        this.isDisabled = false;
        this.isAdd=true;
        this.ruleForm.dataVal='';
        this.drawingList=[];
        this.$Bus.$emit('Loading',true);
        this.getCompanyTree();
       
      })
      //选择所属企业change事件
      this.$Bus.$on('companyChange',(data) =>{
        this.ruleForm.company_id_arr = data;
        this.ruleForm.company_id = data.slice(-1)[0];
        this.$refs.ruleForm.validateField('company_id_arr')//触发form表单中校验所属企业是否选择
        this.ruleForm.case_info_id = '';//清空案场
        this.ruleForm.floor = '';//清空楼层
        this.$Bus.$emit('Loading',true)
        this.getCaseInfo(this.ruleForm.company_id)//获取案场列表
      });
      //外部所属企业change事件 
      this.$Bus.$on('mallChange',data =>{
        this.$Bus.$emit('Loading',true);
        this.waicompany_id_arr=data;
        this.waicompany_id = data.slice(-1)[0];
        this.getCaseInfo(this.waicompany_id,'wai');
      });
    },
    beforeDestroy(){
      this.$Bus.$off('heatmapPopUp');
      this.$Bus.$off('companyChange');
      this.$Bus.$off('mallChange');
    },
    methods: {
     
      //表格序号显示方法
      indexMethod(index){
        return index + 1
      },
      //获取企业树
      getCompanyTree(type='nei'){
        let url = '/sys/report_assist_new/company_tree';
        this.$api.get(url)
        .then(data=>{
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading',false)
            return
          }
          if(data&&data.data){
            recursion(data.data);
            function recursion(val) {
              if(val.length){
                for(let i in val){
                  val[i].value = val[i].id;
                  val[i].label = val[i].company_name;
                  val[i].parent_id_str = val[i].parent_name_list.join('/');
                  if(val[i].children && val[i].children.length){
                    recursion(val[i].children)
                  }else{
                    delete val[i].children
                  }
                }
              }
            }
            if(type=='wai'){
              this.waicompanyOptions=data.data;
              this.waicompany_id_arr.push(data.data[0].id);
              this.waicompany_id=data.data[0].id;
              this.getCaseInfo(data.data[0].id,'wai');
            }
            else{
              this.companyOptions = data.data;
              if(this.isAdd)
              {
                // this.ruleForm.company_id=data.data[0].id;    
                this.ruleForm.company_id=this.waicompany_id;            
              }
              this.ruleForm.company_id_arr.push(this.ruleForm.company_id);
              this.getCaseInfo(this.ruleForm.company_id);
            }
          }
          else{
            if(type=='wai'){
              this.waicompanyOptions=[];
            }
            else{
              this.companyOptions = [];
            }
             this.$Bus.$emit('Loading',false);
          }
         
        })
        .catch(err=>{
           console.log(err);
          if(type=='wai'){
            this.waicompanyOptions=[];
          }
          else{
            this.companyOptions = [];
          }
          this.$Bus.$emit('Loading',false)
        })
      },
      //获取案场列表
      getCaseInfo(id,type='nei'){
        let url = '/sys/report_assist_new/case_list';
        let parmas={
          org_id_list:Array.of(id),
          org_type:1
        }
        if(type=='wai')
        {
          this.waicaseInfoOptions=[];
          this.waicase_info_id='';
        }
        else{
           this.caseInfoOptions = []; 
          //  this.ruleForm.case_info_id='';
        }
        this.$api.post(url,parmas)
        .then(data => {
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading',false)
            return
          }
          //判断接口返回正常
          if(data&&data.data.length)
          {
            if(type=="wai")
            {
              this.waicaseInfoOptions=data.data;
              this.getTableData();
            }
            else{
              this.caseInfoOptions = data.data;
              if(this.isAdd)
              {
                this.ruleForm.case_info_id=data.data[0].id;
              }
              this.getFloor();
              this.getKpis();
            }
          }
          else{ 
            if(type=="wai")
            {
              this.waicaseInfoOptions=[];
              this.waicase_info_id='';
              this.dataTable=[];
            }
            else{
              this.caseInfoOptions = []; 
              this.ruleForm.case_info_id='';     
              this.ruleForm.floor='';
              this.floorOptions = [];     
              this.ruleForm.kpi='';
              this.kpiOptions=[];
            }
            this.$Bus.$emit('Loading',false);
          }
        })
        .catch(err=>{
           console.log(err);
          if(type=="wai")
          {
            this.dataTable=[];
            this.waicaseInfoOptions=[];
            this.waicase_info_id='';
          }
          else{
            this.ruleForm.case_info_id='';
            this.caseInfoOptions = [];      
            this.ruleForm.floor='';
            this.floorOptions = [];   
            this.ruleForm.kpi='';
            this.kpiOptions=[];
          }
          this.$Bus.$emit('Loading',false);
        })
      },
      //选择案场change
      changeCaseInfo(val,type='nei'){
        this.$Bus.$emit('Loading',true);
        if(type=='nei')
        {
          this.getFloor();
          this.getKpis();
        }
        else{
          this.getTableData(false);
        }
      },
      //获得热力图列表
      getTableData(isComp=true){
        let url='sys/thermal/map/list-by-companyid-and-caseinfoid?companyId='+this.waicompany_id;
        if(!isComp){
             url+='&caseInfoId='+this.waicase_info_id;
        }
        this.$api.get(url)
        .then(data=>{
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            return
          }
          if(data&&data.data.length)
          { 
              let _data=data.data;
              let arr=[];
              for(let i in _data)
              {
                arr.push(_data[i]);
              }
              this.dataTable=arr;
          }
          else{
            this.dataTable=[];
          }
          this.$Bus.$emit('Loading',false);
        })
        .catch(err=>{
          this.dataTable=[];
           console.log(err);
        })
      },
      //获取楼层
      getFloor(){
        let url = '/sys/report_assist_new/get-tags-by-caseinfo-id?tagType=4&caseInfoId='+ this.ruleForm.case_info_id
        this.$api.get(url)
        .then(data => {
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading',false)
            return
          }
          // console.log(data);
          //判断接口返回正常
          if(data&&data.data){
            let _data=data.data;
            if(_data){
              let arr=[];
              for(let i in _data){
                let mode={
                  id:_data[i].id,
                  name:_data[i].name
                };
                arr.push(mode)
              }
              this.floorOptions = arr;
              if(this.isAdd)
              {
                this.ruleForm.floor=arr[0].id;
              }
              else{
                let lsarr=arr.filter(x=>{
                  return x.id==this.floorId
                });
                this.ruleForm.floor= lsarr[0].id;               
              }
            }
            else{
              this.ruleForm.floor='';
              this.floorOptions = [];
            }
          }
          else{
            this.ruleForm.floor='';
            this.floorOptions = [];
          }
        })
        .catch(err=>{
           console.log(err);
          this.ruleForm.floor='';
          this.floorOptions = [];
          this.$Bus.$emit('Loading',false)
        })
      },
      //获取指标
      getKpis(){
        let parmas={
          org_id_list:Array.of(this.ruleForm.case_info_id),
          org_type:2,
        }
        let url='/sys/report_assist_new/get_indicator_list';
        this.$api.post(url,parmas)
        .then(data=>{
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading',false)
            return
          }
          if(data&&data.data){
            let _data=data.data;
            let arr=[];
            for(let i in _data){
              let mode={
                id:_data[i].id,
                key:_data[i].key,
                name:_data[i].name,
              };
              arr.push(mode);
            }
            function sortId(a,b){
              return a.id-b.id;
            }
            arr.sort(sortId);
            this.kpiOptions=arr;
            if(this.isAdd)
            {
              this.ruleForm.kpi=arr[0].key;
            }
            else if(!this.ruleForm.kpi){
               this.ruleForm.kpi=arr[0].key;
            }
          }
          else{
            this.ruleForm.kpi='';
            this.kpiOptions=[];
          }
          this.$nextTick(()=>{
            this.$Bus.$emit('Loading',false);
          })
        })
        .catch(err=>{
            console.log(err);
           this.kpiOptions=[];
           this.ruleForm.kpi='';
           this.$Bus.$emit('Loading',false)
        })
      },
      //详情
      heatData(val){
        this.isShow=true;
        this.$Bus.$emit('Loading',true);
        let url='sys/thermal/map/get?id='+val.id;
        this.isAdd=false;
        this.$api.get(url)
        .then(data=>{
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading',false)
            return
          }
          if(data)
          {
            let _data=data.data;
            this.nowId=_data.id;
            console.log(data);
            this.ruleForm.company_id=_data.company_id;
            this.ruleForm.case_info_id=_data.case_info_id;
            this.ruleForm.top_val=_data.top_peak==-1?0:_data.top_peak;
            this.ruleForm.isTop=_data.top_peak==-1?false:true;
            this.ruleForm.radius=_data.radiation_radius?_data.radiation_radius:35;
            this.ruleForm.floor=_data.floor_tag_id;
            this.floorId=_data.floor_tag_id;
            this.ruleForm.kpi=_data.indicator;
            this.ruleForm.dataVal=_data.thermal_map;
            let mode={};
            mode.name='0';
            mode.url=_data.thermal_map;
            this.drawingList=[];
            if(mode.url){
              this.drawingList.push(mode);
            }
            this.getCompanyTree();
          }      
        })
        .catch(err=>{
           console.log(err);
          this.$Bus.$emit('Loading',false)
        })
      },
      //查看图片
      imgPreview(file){
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      //添加图片时
      getFile(file) {
        let isImg=file.raw.type=='image/jpeg' ||file.raw.type=='image/jpg'||file.raw.type=='image/png';
        const isLt5M = file.raw.size / 1024 / 1024 < 5;
        if(!isImg){
           this.$message.error('只能上传图片格式(jpeg,jpg,png)!');
           this.drawingList=[];
           this.ruleForm.dataVal=''
           return
        }
        else if(!isLt5M){
           this.$message.error('图片大小不能超过5M');
           this.drawingList=[];
           this.ruleForm.dataVal=''
           return
        }
        ;
        this.getBase64(file.raw).then(res => {
          if(res) {
            this.drawingShow=true;
            this.ruleForm.dataVal=res;
          }
          else{
            this.$message('error',"图片转base64失败，请重试");
          }
        })
      },
      //删除图片
      imgRemove() {
        this.drawingShow=false;
        this.ruleForm.dataVal='';
      },
      //图片转base64
      getBase64(file) {
        return new Promise(function(resolve, reject) {
          let reader = new FileReader();
          let imgResult = "";
          reader.readAsDataURL(file);
          reader.onload = function() {
            imgResult = reader.result;
          };
          reader.onerror = function(error) {
            reject(error);
          };
          reader.onloadend = function() {
            resolve(imgResult);
          };
        });
      },
      //跳转到配置热力图
      toCoordinate(data){
        let str=data.company_name+'-'+data.case_info_name+'-'+data.floor_tag_name;
        this.$router.push({path:'/coordinate',query:{id:data.id,headtext:str}})
      },
      //保存热力图信息
      confirmDialog(formName){        
        this.$refs[formName].validate((valid)=>{
          if(valid)
          {
            this.$Bus.$emit('Loading',true);
            let dataV={
              case_info_id:this.ruleForm.case_info_id,
              company_id:this.ruleForm.company_id,
              floor_tag_id:this.ruleForm.floor,
              indicator:this.ruleForm.kpi,
              thermal_map:this.ruleForm.dataVal,
              radiation_radius:this.ruleForm.radius,
              top_peak:this.ruleForm.isTop?this.ruleForm.top_val:-1,
            };
            
            if(!this.isAdd)
            {
              dataV.id=this.nowId;
            }
            // this.$Bus.$emit('Loading',false);
            // return 
            let url='sys/thermal/map/save'; 
            this.$api.post(url,dataV)
            .then(data=>{
              if(data == '10001'){
                this.$message.error('无权操作该数据')
                this.$Bus.$emit('Loading',false)
                return
              }
              let mes=this.isAdd?'新增':'修改'
              if(data.msg=='success')
              {
                this.$message({
                  message: mes+"成功",
                  type: "success"
                });
                this.isShow=false;
                if(this.waicase_info_id)
                {
                  this.getTableData(false);
                }
                else
                {
                  this.getTableData();
                }
              }
              else{
                this.$message.error(mes+'失败，请重试');
                this.$Bus.$emit('Loading',false);
              }
            })
            .catch(err=>{
               console.log(err);
              this.$Bus.$emit('Loading',false);
            })
          }
          else{
            return false;
          }
        })
      },
      //删除热力图
      heatDel(id){
        this.$confirm("是否删除？如删除该热力图下所有点位数据将被删除，无法恢复！", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true
        })
        .then(()=>{
          this.$Bus.$emit('Loading',true)
          let url='sys/thermal/map/delete?id='+id;
          this.$api.delete(url)
          .then(data=>{
            if(data == '10001'){
              this.$message.error('无权操作该数据')
              this.$Bus.$emit('Loading',false)
              return
            }
            if(data.msg=='success')
            {
              this.$message({
                message: "删除成功",
                type: "success"
              });
              if(this.waicase_info_id)
              {
                this.getTableData(false);
              }
              else{
                this.getTableData();
              }
            }
            else{
              this.$message({
                message: "删除失败",
                type: "warning"
              });
            }
            this.$Bus.$emit('Loading',false)
          })
          .catch(err=>{
             this.$Bus.$emit('Loading',false)
          })
        })
        .catch(()=>{})
      },

      closeDialog(){
        this.$refs.upload.clearFiles();
        this.$refs.ruleForm.resetFields();
      },
    },
    watch: {}
  }
</script>
